package com.wl.servlets;

import com.wl.fruit.dao.FruitDAO;
import com.wl.fruit.dao.impl.FruitDAOImpl;
import com.wl.fruit.pojo.Fruit;
import com.wl.utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/*
1.保存作用域
	原始情况下，保存作用域可以有四个:
	page 页面级别(现在几乎不用)
	request 一次请求响应范围
	session 一次会话范围
	application 整个应用程序范围
		request.getServletContext();
 */
// servlet从3.0开始支持注解方式的注册
@WebServlet("/index")
public class IndexServlet extends ViewBaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        Integer pageNo = 1;
        HttpSession session = req.getSession();

        String oper = req.getParameter("oper");
        String keyword = null;
        // 判断是否点击查询发送来的请求
        if (!StringUtil.isEmpty(oper) && "search".equalsIgnoreCase(oper)) {
            keyword = req.getParameter("keyword");
            if (StringUtil.isEmpty(keyword)) {
                keyword = "";
            }
            session.setAttribute("keyword", keyword);
        } else {
            String pageNoStr = req.getParameter("pageNo");
            if (!StringUtil.isEmpty(pageNoStr)) {
                pageNo = Integer.parseInt(pageNoStr);
            }
            Object keywordObj = session.getAttribute("keyword");
            if (keywordObj != null) {
                keyword = String.valueOf(keywordObj);
            } else {
                keyword = "";
            }
        }

        session.setAttribute("pageNo", pageNo);
        FruitDAO fruitDAO = new FruitDAOImpl();
        List<Fruit> fruitList = fruitDAO.getFruitList(keyword, pageNo);
        // 总记录数
        Long fruitCount = fruitDAO.getFruitCount(keyword);
        // 总条数
        Long pageCount = (fruitCount + 5 - 1) / 5;
        session.setAttribute("pageCount", pageCount);

        // 保存到session
        req.getSession().setAttribute("fruitList", fruitList);
        // 此处的视图名称为index
        // 那么thymeleaf会将这个逻辑视图名称对应到物理视图名称上
        // 逻辑视图: index 物理视图: view-prefix + 逻辑视图名称 + view-suffix
        // 真实视图名称 /index.html
        super.processTemplate("index", req, resp);
    }
}
